package com.web.controller.lxf;

import com.core.dto.TestDTO;
import com.core.model.lxf.SecKillGoods;
import com.core.model.user.Order;
import com.core.shared.Log;
import com.dao.LxfDao;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.service.LxfService;
import com.web.controller.AbstractController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.*;


/**
 * Created with IntelliJ IDEA.
 * User: xianfei
 * Date: 2016-01-07
 * Time: 16:29
 * To change this template use Editor | File and Code Templates.
 */
@Controller()
@RequestMapping(value = "/lxf")
public class LxfController extends AbstractController {

    @Autowired
    private LxfService lxfService;
    @Autowired
    private MongoOperations mongo;

    @Autowired
    private LxfDao lxfDao;

    @RequestMapping(value = "user_info/{guid}", method = RequestMethod.GET)
    @ResponseBody
    public Object findUserInfo(@PathVariable String guid) {
        return lxfService.findUserInfoByUserGuid(guid);
    }

    @RequestMapping(value = "addgood")
    public void addGood() {
        lxfService.addGood();
    }

    @RequestMapping(value = "goodtype")
    public void goodType() {
        lxfService.findGoodType();
    }

    @RequestMapping(value = "mongo")
    public void saveMongoData() {
        Order order = new Order("1", "刘仙飞", "doc");
        mongo.save(order);
    }

    @RequestMapping(value = "find_by_mongo")
    @ResponseBody
    public Object findByMongo() {
        Log.getLogger(this.getClass()).debug("");
        return mongo.findAll(Order.class);
    }

    @RequestMapping("test")
    @CrossOrigin(origins = "*", maxAge = 3600)
    public String testSecurity() {
        SecKillGoods goods = new SecKillGoods(10, "秒杀商品");
        lxfService.saveSecKillGoods(goods);
        return "front/mySecurity";
    }

    @RequestMapping(value = "sec_kill/{id}/{num}", method = RequestMethod.GET)
    @ResponseBody
    public String SecKill(@PathVariable String id, @PathVariable String num) throws InterruptedException {
        SecKillGoods good = lxfService.findById(id);
        if (good != null && good.remainNum() >= Integer.parseInt(num)) {
            Thread.sleep(1000);
            if (good.remainNum() > 0) {
                int i = lxfService.reduceStock(id, Integer.parseInt(num));
                if (i != 0) {
                    lxfService.generateOrder("lxf", id, Integer.parseInt(num));
                    return "购买成功";
                } else {
                    return "购买失败，库存不足";
                }
            } else {
                return "购买失败，库存不足";
            }
        }
        return "购买失败，库存不足";
    }

    @RequestMapping("sec_skill")
    @ResponseBody
    public String secKillTest() {
        final SimpleClientHttpRequestFactory httpRequestFactory = new SimpleClientHttpRequestFactory();
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build();
        ExecutorService service = new ThreadPoolExecutor(5, 200, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
        for (int i = 0; i < 50; i++) {
            service.execute(() -> {
                ClientHttpRequest request = null;
                try {
                    URI uri = new URI("http://localhost/lxf/sec_kill/1/1");
                    request = httpRequestFactory.createRequest(uri, HttpMethod.GET);
                    InputStream body = request.execute().getBody();
                    BufferedReader br = new BufferedReader(new InputStreamReader(body));
                    String line = "";
                    String result = "";
                    while ((line = br.readLine()) != null) {
                        result += line;
                    }
                    System.out.println("result: " + result);
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            });
            /*new Thread(new Runnable() {
                @Override
                public void run() {
                    ClientHttpRequest request = null;
                    try {
                        URI uri = new URI("http://localhost/lxf/sec_kill/1/1");
                        request = httpRequestFactory.createRequest(uri, HttpMethod.GET);
                        InputStream body = request.execute().getBody();
                        BufferedReader br = new BufferedReader(new InputStreamReader(body));
                        String line = "";
                        String result = "";
                        while ((line = br.readLine()) != null) {
                            result += line;
                        }
                        System.out.println("result: " + result);
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }).start();*/
        }
        return "simulationCocurrentTakeOrder";
    }


    @RequestMapping(value = "service")
    @ResponseBody
    public Object service() {
        return new TestDTO("lxf", null);
    }
}
